package com.way2sms.way2inbox;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.CountDownTimer;
import android.provider.Telephony;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import android.os.Handler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.TreeSet;
import java.util.UUID;
import java.util.regex.Pattern;

import www.way2inbox.adapter.SMSchatlistadapter;
import www.way2inbox.comm.Errorcode;
import www.way2inbox.comm.ReadWebpageAsyncTask;
import www.way2inbox.comm.SessionManager;
import www.way2inbox.comm.TaskListener;
import www.way2inbox.common.Constants;
import www.way2inbox.common.IsOnline;
import www.way2inbox.common.PrintMsg;
import www.way2inbox.common.Urls;
import www.way2inbox.data.Native_DatabaseHelper;
import www.way2inbox.data.item;
import www.way2inbox.data.smsfetch;
import www.way2inbox.settings.DeviceDetailsClass;


public class ComposeSmsActivity extends ActionBarActivity implements View.OnClickListener,TaskListener {

    RelativeLayout OperatorLayout, BackLayout, SmileyLayout, SendLayout, SMS_count,Edit_Bottom,BackBottom;
    LinearLayout ChatLayout;
    EditText MessageText;
    TextView LeftCha, CarrierStatus;
    Boolean CarrierW2S = true;
    String Number, DisplayName;
    String CarrierSt;
    SharedPreferences UserCredentials;
    Boolean W2SQuota;
    Native_DatabaseHelper helper;
    ArrayList<item> list;
    SMSchatlistadapter adapter;
    int ChatBottomlayout;
    InputFilter filter;
    ListView lv;

    public boolean isAlpha(String name) {
        return name.matches("[0-9+]+");
    }
    int sms_count=0,sms_width,sms_remain_to_next,sms_encoding;
    Native_DatabaseHelper smsDb;
    SharedPreferences SH_notif;
    SharedPreferences.Editor sh_editor;
    String myPackageName;
    DeviceDetailsClass detailsclass;
    RelativeLayout default_application;
    @TargetApi(Build.VERSION_CODES.KITKAT)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_sms);

        myPackageName = getPackageName();
         detailsclass=new DeviceDetailsClass(this);
        default_application=(RelativeLayout)findViewById(R.id.default_application);
        default_application.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new
                        AlertDialog.Builder(ComposeSmsActivity.this);
                builder.setMessage(
                        "Way2Inbox is not set as your default messaging app. Do you want to set it default?")
                        .setCancelable(false)
                        .setTitle("Alert!")
                        .setNegativeButton("No",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        default_application.setVisibility(View.GONE);

                                    }
                                }).setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            @TargetApi(19)
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                default_application.setVisibility(View.GONE);
                                Intent intent = new Intent(
                                        Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);

                                intent.putExtra(
                                        Telephony.Sms.Intents.EXTRA_PACKAGE_NAME,
                                        getPackageName());
                                PrintMsg.setLogerror(ComposeSmsActivity.this,"Package name is :"+getPackageName());
                                startActivity(intent);

                            }
                        });
                builder.show();
            }
        });
        Intent FromSMS = getIntent();
        Number = FromSMS.getStringExtra("MobileNo");
        DisplayName = FromSMS.getStringExtra("MobileName");
        PrintMsg.setLogerror(ComposeSmsActivity.this, "Details : " + Number + "----" + DisplayName);

        UserCredentials = getApplicationContext().getSharedPreferences(getResources().getString(R.string.USRD), 0);
        W2SQuota = UserCredentials.getBoolean(getResources().getString(R.string.W2SQuota), false);

        //CLEARING PUSH NOTIFICATION OF THIS NUMEBR..
        smsDb =new Native_DatabaseHelper(this);
        smsDb.RemovePush(Number);

        //SETING MOBILE NUMBER FOR PUSH NOTIFICATION , IF SAME NUMBER OCCUR NOTIFICATION WILL NOT DISPLAY..
        SH_notif =getApplicationContext().getSharedPreferences("ChatRoomNumber", 0);
        sh_editor=SH_notif.edit();
        sh_editor.putString("ChatNO",Number);
        sh_editor.commit();
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(this.NOTIFICATION_SERVICE);
        nMgr.cancelAll();




        //ACTION BAR SETTING UP..
        ActionBar actionBar = getSupportActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.AppColor)));
        if (DisplayName != null && !DisplayName.equalsIgnoreCase("NONE")) {
            actionBar.setTitle(DisplayName);
        } else {
            actionBar.setTitle(Number);
        }
        actionBar.setDisplayHomeAsUpEnabled(false);

        BackBottom      =(RelativeLayout) findViewById(R.id.BackBottom);
        OperatorLayout = (RelativeLayout) findViewById(R.id.Operator_Selector);
        BackLayout = (RelativeLayout) findViewById(R.id.Chat_Back);
        SmileyLayout = (RelativeLayout) findViewById(R.id.Chat_Smily);
        SendLayout = (RelativeLayout) findViewById(R.id.Chat_send);
        ChatLayout = (LinearLayout) findViewById(R.id.ChatLayout);
        Edit_Bottom= (RelativeLayout) findViewById(R.id.Edit_Bottom);

        LeftCha = (TextView) findViewById(R.id.setSMScount);
        CarrierStatus = (TextView) findViewById(R.id.CarrierStatus);
        MessageText = (EditText) findViewById(R.id.Chat_msg);





        // CHECKING IF ADDRESS IS VALID OR NOT , IF NOT VALID ,USER CAN'T SEND SMS FROM HERE.

        PrintMsg.SetToast(ComposeSmsActivity.this," Valid No :"+isAlpha(Number),0);
        if(!isAlpha(Number)){
            Edit_Bottom.setVisibility(View.INVISIBLE);
            BackBottom.setVisibility(View.VISIBLE);
        }


        //SETTING UP CARRIER HERE AS DEFAULT..
        if (CarrierW2S) {

            //CARRIER IS NOW WAY2SMS
            if (!W2SQuota) {
                CarrierW2S = false;
                CarrierStatus.setText(getResources().getString(R.string.Carrier_W2S));
                MessageText.setHint(getResources().getString(R.string.Send_m1));
            } else {
                CarrierStatus.setText(getResources().getString(R.string.Quota_full));
                MessageText.setHint(getResources().getString(R.string.Send_m3));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        CarrierStatus.setText(getResources().getString(R.string.Carrier_LocalSMS));

                        CarrierW2S = false;

                    }
                }, 1 * 5000);

            }

        } else {
            //CARRIER IS NOW SMS
            CarrierW2S = true;
            CarrierStatus.setText(getResources().getString(R.string.Carrier_LocalSMS));
            MessageText.setHint(getResources().getString(R.string.Send_m3));
        }

        /*
        * Processing Chat MEssage ...
        * */
        ChatBottomlayout=60;

        filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; ++i)
                {
                    if (!Pattern.compile("[ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890]*").matcher(String.valueOf(source.charAt(i))).matches())
                    {
                        return "";
                    }
                }

                return null;
            }
        };

        CarrierSt=getResources().getString(R.string.Carrier_W2S);

        MessageText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length()>0){
                    LeftCha.setVisibility(View.VISIBLE);
                    if(CarrierStatus.getText().toString().equalsIgnoreCase(CarrierSt)) {
                        LeftCha.setText(String.valueOf(s.length()) + "/140");

                        if(MessageText.getLineCount()>1 && MessageText.getLineCount()<=5) {
                            ChatLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ChatBottomlayout + (MessageText.getLineCount() * 20)));
                        }
//                        MessageText.setHeight(MessageText.getHeight()+(MessageText.getLineCount()*10));
                        if(s.length()==140){
                            int maxLength =140;
                            InputFilter[] FilterArray = new InputFilter[1];
                            FilterArray[0] = new InputFilter.LengthFilter(maxLength);
                            MessageText.setFilters(FilterArray);
//                            MessageText.setFilters(new InputFilter[]{filter,new InputFilter.LengthFilter(140)});

                        }

                        Log.e("MEASURES :","--> Height :"+((ChatBottomlayout+(MessageText.getLineCount()*10)))+"\n Linecount :"+(MessageText.getLineCount()));




                    }else{
                        if(MessageText.getLineCount()>1 && MessageText.getLineCount()<=5) {
                            ChatLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ChatBottomlayout + (MessageText.getLineCount() * 20)));
                        }
                        int[] ii = SmsMessage.calculateLength(s, false);
                        sms_count=ii[0];
                        sms_width=ii[1];
                        sms_remain_to_next=ii[2];
                        sms_encoding=ii[3];

                        LeftCha.setText("("+Integer.toString(sms_count)+")"+sms_remain_to_next);
                    }
                }else{
                    LeftCha.setVisibility(View.GONE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        //SETTING FOR CARRIER HERE..
        OperatorLayout.setOnClickListener(this);
//        CarrierStatus.setText(getResources().getString(R.string.Plz_carrier));

        //CHECKING FOR CARRIER AND SENDING MESSAGE NOW
        SendLayout.setOnClickListener(this);
        BackLayout.setOnClickListener(this);
        BackBottom.setOnClickListener(this);

        LoadListView();

     new UpdateReadStateTask().execute();
    }


    public void LoadListView(){
        helper = new Native_DatabaseHelper(this);

        lv = (ListView) findViewById(R.id.ChatRoomListview);
        list = (ArrayList<item>) helper.stickyheader(Number);

        adapter = new SMSchatlistadapter(ComposeSmsActivity.this,list);
        lv.setAdapter(adapter);
    }


    private void SendingSMS(String Number,String SMStype,String Message) {

        if(SMStype.equalsIgnoreCase("LocalSMS")){
            PrintMsg.setLogerror(ComposeSmsActivity.this,"Sending Local SMS :"+Number+"----"+Message);
            sendLocalSMS(Number, Message);
        }else{
            PrintMsg.setLogerror(ComposeSmsActivity.this,"Sending Way2SMS SMS :"+Number+"----"+Message);
            sendWa2sms(Number, Message);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_send_sm, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }

        return super.onOptionsItemSelected(item);
    }
public void onBackPressed(){
    super.onBackPressed();
}


    JSONObject SendSms=null;
    SessionManager session;
    String UserName,fromMobile,Token,MID;
    ReadWebpageAsyncTask readAsyncTask;
    //SENDING SMS VIA WAY2ONLINE ...
    public void sendWa2sms(String ReceiverNo,String Message){
        session = new SessionManager(getApplicationContext());
        // Decrypting the token for values
        HashMap<String, String> user = session.getUserDetails();
        UserName = user.get(SessionManager.KEY_NAME);
        fromMobile = user.get(SessionManager.KEY_Mobile);
        Token = user.get(SessionManager.KEY_TOKEN);

        /* Retrive Device ID */
        try {
            TelephonyManager phonespecs = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            MID = phonespecs.getDeviceId();
            String macAddr = "", androidId = "";
            if (MID == null) {
                WifiManager wifiMan = (WifiManager) this
                        .getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInf = wifiMan.getConnectionInfo();
                macAddr = wifiInf.getMacAddress();
                androidId = ""
                        + android.provider.Settings.Secure
                        .getString(
                                getContentResolver(),
                                android.provider.Settings.Secure.ANDROID_ID);
                UUID deviceUuid = new UUID(androidId.hashCode(),
                        macAddr.hashCode());
                MID = deviceUuid.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Urls url=new Urls();
        readAsyncTask = new ReadWebpageAsyncTask(ComposeSmsActivity.this);
        SendSms= new JSONObject();
PrintMsg.SetToast(ComposeSmsActivity.this,"Sending via W2s",0);
        try{

//            PrintMsg.setLogerror(SendSMS.this,"TOKEN :"+Token+"Sender NO :"+ReceiverNo+"My No :"+fromMobile.toString()+"Message :"+Message+"MID :"+MID);
            SendSms.put("TK", Token);
            SendSms.put("RNO", ReceiverNo);
            SendSms.put("MNO",fromMobile.toString());
            SendSms.put("MSG", Message);
            SendSms.put("MID", MID);


            if(!IsOnline.getConnection(ComposeSmsActivity.this)){
                PrintMsg.SetToast(ComposeSmsActivity.this, getResources().getString(R.string.NoInternet), 1);
                return;
            }else {

                readAsyncTask.execute(SendSms,
                        url.SendSMS);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onResume(){
        super.onResume();
        LoadListView();
        if(detailsclass.getversion()) {
            if (!detailsclass.getdefaultpackage(myPackageName)) {
                default_application.setVisibility(View.VISIBLE);
            }else{
                default_application.setVisibility(View.GONE);
            }
        }
    }
    //---sends an SMS message to another device---
    private void sendLocalSMS(String phoneNumber, String message)
    {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

        final PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= Build.VERSION_CODES.KITKAT){
            // Do something for KITKAT and above versions
            ContentValues values = new ContentValues();
            PrintMsg.setLogerror(ComposeSmsActivity.this,"Way2SMS message "+Number+"---"+savemessage);
            values.put("address", Number);
            values.put("body",savemessage );
            values.put("read","1");
            values.put("subject","SMS");
            values.put("date",System.currentTimeMillis());
            getApplicationContext().getContentResolver().insert(Uri.parse("content://sms/sent"),values);
        }

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
        LoadListView();
    }

    @Override
    public void onClick(View v) {
        System.out.println("----->"+v.getId());
        switch(v.getId()){
            case R.id.Operator_Selector:

                    if (CarrierW2S) {

                        //CARRIER IS NOW WAY2SMS
                        if (!W2SQuota) {
                            CarrierW2S = false;
                            CarrierStatus.setText(getResources().getString(R.string.Carrier_W2S));
                            MessageText.setHint(getResources().getString(R.string.Send_m1));
                        } else {
                            CarrierStatus.setText(getResources().getString(R.string.Quota_full));
                            MessageText.setHint(getResources().getString(R.string.Send_m3));
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    CarrierStatus.setText(getResources().getString(R.string.Carrier_LocalSMS));

                                    CarrierW2S = false;

                                }
                            }, 1 * 5000);

                        }

                    } else {
                        //CARRIER IS NOW SMS
                        CarrierW2S = true;
                        CarrierStatus.setText(getResources().getString(R.string.Carrier_LocalSMS));
                        MessageText.setHint(getResources().getString(R.string.Send_m3));
                    }


                break;

            case R.id.Chat_send:
                PrintMsg.SetToast(ComposeSmsActivity.this,"Clicked",1);
//                Number="9676462929";
                if(Number!=null) {
                    if(MessageText.length()>0) {
                        ChatLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getResources().getInteger(R.integer.ChatBottomHt)));

                        savemessage=MessageText.getText().toString();
                        if (CarrierStatus.getText().toString().equalsIgnoreCase(getResources().getString(R.string.Carrier_LocalSMS))) {
                            smsfetch obj=new smsfetch("",Number,"",MessageText.getText().toString(),"1","0",String.valueOf(System.currentTimeMillis()),"2","1","SMS");
                            list.add(obj);
                            adapter.notifyDataSetChanged();
                            SendingSMS(Number, "LocalSMS", MessageText.getText().toString());
                            LoadListView();
                        } else {

                            try {
                                Number = Number.substring(Number.length() - 10,Number.length());
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            if (Number.substring(0, 1).matches(Constants.Validno)) {

                                smsfetch obj = new smsfetch("", Number, "", MessageText.getText().toString(), "1", "0", String.valueOf(System.currentTimeMillis()), "2", "1","Way2SMS");
                                list.add(obj);
                                adapter.notifyDataSetChanged();
                                SendingSMS(Number, "W2S", MessageText.getText().toString());
                                LoadListView();
                            }else {
                                    PrintMsg.SetToast(ComposeSmsActivity.this, getResources().getString(R.string.NomatchNO), 1);

                            }
                        }
                    }else{
                        PrintMsg.SetToast(ComposeSmsActivity.this,getResources().getString(R.string.NoSendMessage),1);
                    }
                }else{
                    PrintMsg.SetToast(ComposeSmsActivity.this,getResources().getString(R.string.SendnoNumber),1);
                }


                MessageText.setText("");

                break;

            case R.id.Chat_Back:
                Intent Back = new Intent(ComposeSmsActivity.this,Messages.class);
                startActivity(Back);
                finish();
                break;

            case R.id.BackBottom:
                Intent Backk = new Intent(ComposeSmsActivity.this,Messages.class);
                startActivity(Backk);
                finish();
                break;

        }
    }

    @Override
    public void onTaskStarted() {

    }
    String savemessage;

    @Override
    public void onTaskFinished(String result) {
        Errorcode ec= new Errorcode();


        JSONObject jsvn=null;
        try {
            jsvn=new JSONObject(result.toString());
            PrintMsg.setLogerror(ComposeSmsActivity.this,"Response : -----------"+jsvn.toString());
            if(jsvn.get("CD").toString().equals("05")){

                    ContentValues values = new ContentValues();
                    PrintMsg.setLogerror(ComposeSmsActivity.this,"Way2SMS message "+Number+"---"+savemessage);
                    values.put("address", Number);
                    values.put("body",savemessage );
                    values.put("subject","Way2SMS" );
                    values.put("type","2");
                    values.put("date",System.currentTimeMillis());
                    getApplicationContext().getContentResolver().insert(Uri.parse("content://sms/sent"),values);



                LoadListView();

            }


        } catch(JSONException e){
            e.printStackTrace();
        }
    }

//    private static final int TYPE_ITEM = 0;
//    private static final int TYPE_SEPARATOR = 1;
//    class myadapter extends BaseAdapter {
//        ArrayList<item> msg_list=new ArrayList<item>();;
//        private TreeSet<Integer> sectionHeader = new TreeSet<Integer>();
//
//        public myadapter(ArrayList<item> list) {
//            msg_list = list;
//        }
//
//        @Override
//        public int getCount() {
//            // TODO Auto-generated method stub
//            return msg_list.size();
//        }
//
//        @Override
//        public Object getItem(int position) {
//            // TODO Auto-generated method stub
//            return msg_list.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            // TODO Auto-generated method stub
//            return position;
//        }
//
//        public void addItem(final smsfetch item) {
//            msg_list.add(item);
//            notifyDataSetChanged();
//        }
//
//        public void addSectionHeaderItem(final smsfetch item) {
//            msg_list.add(item);
//            sectionHeader.add(msg_list.size() - 1);
//            notifyDataSetChanged();
//        }
//        String prevDate =null;
//        @Override
//        public View getView(int position, View convertView, ViewGroup parent) {
//            // TODO Auto-generated method stub
//            holder viewHolder;
//            View v = convertView;
//            int rowType = getItemViewType(position);
//            if (convertView == null) {
//                LayoutInflater li = (LayoutInflater) ComposeSmsActivity.this
//                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//                viewHolder = new holder();
//                        v = li.inflate(R.layout.adapter_chat_in_out, null);
//                        viewHolder.Chat_in_msg = (TextView) v.findViewById(R.id.Chat_in_msg);
//                        viewHolder.Chat_out_msg = (TextView) v.findViewById(R.id.Chat_out_msg);
//                        viewHolder.Chat_in_time=(TextView)v.findViewById(R.id.Chat_In_times);
//                        viewHolder.Chat_out_time=(TextView)v.findViewById(R.id.Chat_Out_times);
//                        viewHolder.Chat_in_Fromtype=(TextView)v.findViewById(R.id.Chat_In_FromType);
//                        viewHolder.Chat_out_Fromtype=(TextView)v.findViewById(R.id.Chat_out_FromType);
//                        viewHolder.Chat_in = (RelativeLayout) v.findViewById(R.id.Chat_in);
//                        viewHolder.Chat_out = (RelativeLayout) v.findViewById(R.id.Chat_out);
//
//                        viewHolder.Headerdate= (TextView) v.findViewById(R.id.Headerdate);
//                v.setTag(viewHolder);
//            } else {
//                viewHolder = (holder) v.getTag();
//            }
//
//
////            viewHolder.out_messages = (RelativeLayout) v.findViewById(R.id.out_messages);
//            smsfetch model = msg_list.get(position);
//
//
//
//            if (model.getFolderName().contentEquals("2")) {
//                viewHolder.Chat_in.setVisibility(View.VISIBLE);
//                viewHolder.Chat_out.setVisibility(View.GONE);
//                viewHolder.Chat_in_msg.setText(model.getMsg());
////
//                viewHolder.Chat_in_time.setText(getTime(Long.valueOf(model.getTime())));
//                viewHolder.Chat_in_Fromtype.setText("SMS");
//                System.out.println("sent");
//
//
//                //SETUP FOR FROM SIM/WAY2SMS TO TEXT FIELD..
//
//                if(model.get_subject()!=null) {
//                    if (model.get_subject().equalsIgnoreCase("Way2SMS")) {
//                        viewHolder.Chat_out_Fromtype.setText("Way2SMS");
//                    } else {
//                        viewHolder.Chat_out_Fromtype.setText("SMS");
//                    }
//                }
//            } else if (model.getFolderName().equals("1")) {
//
//                viewHolder.Chat_in.setVisibility(View.GONE);
//                viewHolder.Chat_out.setVisibility(View.VISIBLE);
//                viewHolder.Chat_out_msg.setText(model.getMsg());
////
//                viewHolder.Chat_out_time.setText(getTime(Long.valueOf(model.getTime())));
//                viewHolder.Chat_out_Fromtype.setText("");
//                //System.out.println("inbox   "+model.getMsg());
//            }
////            if(model.get_subject()!=null){
////            if (model.get_subject().equalsIgnoreCase("Way2SMS")) {
////                viewHolder.Chat_in.setVisibility(View.VISIBLE);
////                viewHolder.Chat_out.setVisibility(View.GONE);
////                viewHolder.Chat_in_msg.setText(model.getMsg());
//////
////                viewHolder.Chat_in_time.setText(getTime(Long.valueOf(model.getTime())));
////
////                //SETUP FOR FROM SIM/WAY2SMS TO TEXT FIELD..
////                viewHolder.Chat_in_Fromtype.setText("Way2SMS");
////                System.out.println("sent");
////            }
//
//
//
//
////            }
//
//
//
//            return v;
//        }
//
//
//
//        private String getTime(Long currentDateTime) {
//            try {
////                long currentDateTime = System.currentTimeMillis();
//
//                //creating Date from millisecond
//                Date currentDate = new Date(currentDateTime);
//
//                //printing value of Date
//                System.out.println("current Date: " + currentDate);
//
//                DateFormat df = new SimpleDateFormat("HH:mm a");
//
//                //formatted value of current Date
//                System.out.println("Milliseconds to Date: " + df.format(currentDate));
//
//                //Converting milliseconds to Date using Calendar
//                Calendar cal = Calendar.getInstance();
//                cal.setTimeInMillis(currentDateTime);
//                System.out.println("Milliseconds to Date using Calendar:"
//                        + df.format(cal.getTime()));
//
//                //copying one Date's value into another Date in Java
//                Date now = new Date();
//                Date copiedDate = new Date(now.getTime());
//                res=df.format(cal.getTime());
//
//                System.out.println("original Date: " + df.format(now));
//
//
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            return res;
//        }
//
//    }
//
//    class holder {
//
//        public TextView Chat_in_msg,Chat_in_time,Chat_in_Fromtype,Headerdate;
//        public TextView Chat_out_msg,Chat_out_time,Chat_out_Fromtype;
//        public TextView dateIn, dateout;
//        public RelativeLayout Chat_in, Chat_out, out_messages;
//    }
    String res;
    private String getDateheader(Long dbtime){
        DateFormat df = new SimpleDateFormat("M dd, yyyy");
        //Converting milliseconds to Date using Calendar
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(dbtime);
        res=df.format(cal.getTime());
        return res;
    }
    class UpdateReadStateTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < list.size(); i++) {
                item itm=list.get(i);
                if(!itm.isSection()){
                    smsfetch model=(smsfetch)itm;
                    if(model.getReadState().equals("0")){
                        Uri uri = Uri.parse("content://sms/inbox");
                        String selection = "(address = '"+model.getAddress()+"' or address = '+91"+model.getAddress()+"' ) AND body = ? AND read = ?";
                        String[] selectionArgs = { model.getMsg(), "0"};
                        ContentValues values = new ContentValues();
                        values.put("read", true);
                        ComposeSmsActivity.this.getContentResolver().update(uri, values, selection, selectionArgs);
                        System.out.println("updated msg "+model.getMsg());
                    }
                }

            }
            return null;
        }


    }




    @Override
    public void onStart(){
        super.onStart();
        adapter.notifyDataSetChanged();
        LocalBroadcastManager.getInstance(this).registerReceiver((mMessageReceiver), new IntentFilter(Constants.FILTER));
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("KBR", "Got message");
            handleMessage(intent);
        }
    };
    private void handleMessage(Intent msg)
    {
        Bundle data = msg.getExtras();
        switch (data.getInt(Constants.COMMAND, 0))
        {
            case Constants.UPDATE_PROGRESS:
                int progress = data.getInt(Constants.DATA, 0);
                if(progress==5) {
                    LoadListView();
                    new UpdateReadStateTask().execute();
                    adapter.notifyDataSetChanged();
                }

                break;

            default:
                break;
        }
    }

    public void onStop(){
        super.onStop();

        SH_notif =getApplicationContext().getSharedPreferences("ChatRoomNumber", 0);
        sh_editor=SH_notif.edit();
        sh_editor.clear();
        sh_editor.commit();
    }

}
